<template>
  <div style="border: 1px solid #ccc; z-index: 100;">
    <!-- 工具栏 -->
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <!-- 编辑器 -->
    <Editor
      :style="{ height: props.height + 'px', overflowY: 'hidden' }"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: [Number, String],
    default: 400
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
const valueHtml = ref(props.modelValue)

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  valueHtml.value = newVal
})

// 监听valueHtml变化并触发事件
watch(valueHtml, (newVal) => {
  emit('update:modelValue', newVal)
})

// 工具栏配置
const toolbarConfig = {}

// 编辑器配置
const editorConfig = {
  placeholder: props.placeholder
}

// 编辑器创建回调
const handleCreated = (editor: any) => {
  editorRef.value = editor
}

// 编辑器内容变化回调
const handleChange = (editor: any) => {
  valueHtml.value = editor.getHtml()
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 设置编辑器内容
const setHtml = (html: string) => {
  valueHtml.value = html
}

// 获取编辑器内容
const getHtml = () => {
  return valueHtml.value
}

// 清空编辑器内容
const clear = () => {
  valueHtml.value = ''
}

// 暴露方法给父组件
defineExpose({
  setHtml,
  getHtml,
  clear
})
</script>

<style scoped>
/* 可以在这里添加自定义样式 */
</style>